package com.pomelo.kill.controller;

import com.pomelo.kill.common.AjaxResult;
import com.pomelo.kill.exception.KillException;
import com.pomelo.kill.model.Car;
import com.pomelo.kill.model.Goods;
import com.pomelo.kill.model.Order;
import com.pomelo.kill.service.CarService;
import com.pomelo.kill.service.RedisService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/kill")
public class KillController {

    @Resource
    private RedisService redisService;

    @Resource
    private CarService carService;

    /**
     * 获取所有秒杀商品信息
     *
     * @return 秒杀商品信息
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<Goods> list = redisService.GetAllKillData();
        return list.size() > 0 ? AjaxResult.success(list) : AjaxResult.failure("查询失败");
    }

    /**
     * 用户提交订单，生成订单，状态为未支付，放到redis，暂时从redis删除，确认付款之后再修改订单状态，加入数据库，删除库存
     *
     * @param uid 用户编号
     * @param gid 商品编号
     * @return 订单信息
     */
    @RequestMapping("/sc")
    public AjaxResult kill(Integer uid, Integer gid, Integer state) {
        try {
            Order order = redisService.order(uid, gid, state);
            return order == null ? AjaxResult.failure("提交失败") : AjaxResult.success(order);
        } catch (KillException e) {
            return AjaxResult.failure(e.getMessage());
        }
    }

    /**
     * 未付款订单进行付款
     *
     * @param id 未付款订单编号
     * @return 支付成功订单信息
     */
    @RequestMapping("/pay")
    public AjaxResult pay(String id) {
        try {
            Order pay = redisService.pay(id);
            return pay == null ? AjaxResult.failure("支付失败") : AjaxResult.success(pay);
        } catch (KillException e) {
            return AjaxResult.failure(e.getMessage());
        }
    }

    /**
     * 未付款订单取消
     *
     * @param id 要取消的订单id
     */
    @RequestMapping("/cancel")
    public AjaxResult cancel(String id) {
        int cancel = redisService.cancel(id);
        return cancel == 0 ? AjaxResult.failure("取消失败") : AjaxResult.success();
    }

    /**
     * 购物车商品付款
     */
    @RequestMapping("/carToPay")
    public AjaxResult carToPay(@RequestBody Car car) {
        try {
            Order order = redisService.order(car.getUid(), car.getGid(), null);
            // 购物车中删除
            carService.deleteByPrimaryKey(car.getId());
            return order == null ? AjaxResult.failure("提交订单失败") : AjaxResult.success(order);
        } catch (KillException e) {
            return AjaxResult.failure(e.getMessage());
        }
    }


}
